<template>
  <div class="video-interview-container">
      <!-- 摄像头授权弹窗 -->
      <div class="permission-modal" v-if="showPermissionModal">
          <div class="modal-content">
              <div class="modal-header">
                  <img src="@/assets/images/interview/camera.png" alt="摄像头" class="modal-icon">
                  <h2>摄像头授权</h2>
              </div>
              <div class="modal-body">
                  <p>为了提供更好的面试体验，我们需要开启您的摄像头并录制面试全程。</p>
                  <p>录制内容<strong>仅用于</strong>分析面试表现和提供反馈，不会用于其他目的。</p>
                  <p>您的隐私对我们至关重要，所有数据将被严格保密。</p>

                  <!-- 错误提示 -->
                  <div v-if="permissionError" class="error-message">
                      <p>{{ errorMessage }}</p>
                      <p>请尝试以下解决方案：</p>
                      <ul>
                          <li>使用<strong>localhost</strong>而非IP地址访问应用</li>
                          <li>确保浏览器允许访问摄像头</li>
                          <li>如果使用Chrome，检查chrome://flags中的不安全上下文设置</li>
                      </ul>
                  </div>
              </div>
              <div class="modal-footer">
                  <button class="cancel-btn" @click="handleCancel">返回</button>
                  <button class="confirm-btn" @click="handleConfirm">{{ permissionError ? '重试' : '确认授权' }}</button>
              </div>
          </div>
      </div>

      <!-- 退出确认弹窗 -->
      <div class="permission-modal" v-if="showExitConfirmModal">
          <div class="modal-content">
              <div class="modal-header">
                  <h2>确认退出面试</h2>
              </div>
              <div class="modal-body">
                  <p>您确定要退出当前面试吗？</p>
                  <p>退出后，当前面试进度将<strong>不会</strong>保存。</p>
              </div>
              <div class="modal-footer">
                  <button class="cancel-btn" @click="cancelExit">取消</button>
                  <button class="confirm-btn exit-btn" @click="confirmExit">确认退出</button>
              </div>
          </div>
      </div>

      <!-- 面试视频区域 (在用户确认授权后显示) -->
      <div class="video-section" v-if="!showPermissionModal">
          <!-- 返回按钮 -->
          <div class="back-button" @click="showExitConfirm">
              <i class="back-icon"></i>
              <span>返回</span>
          </div>

          <div class="interview-container" :class="{ 'switched': videoPositionSwitched }">
              <!-- 背景图区域 -->
              <div class="background-area" @click="switchPosition">
                  <!-- <img src="@/assets/images/interview/talk.jpg" alt="面试背景" class="background-image"> -->
                  <virtualhuman v-model="word"></virtualhuman>
              </div>

              <!-- 视频区域 -->
              <div class="video-area" @click="switchPosition">
                  <video ref="userVideo" autoplay muted playsinline class="user-video"></video>
              </div>

              <!-- 语音图标 -->
              <div class="sound-icon-container">
                <!-- <el-input :readonly="true" id="word" v-model="word"></el-input> -->
                  <img @click="audioCHangeWord" src="@/assets/images/interview/sound.png" alt="语音" class="sound-icon">
                  <div v-if="isStartFace" style="margin-right: 10px;" >
                    <div class="sound-wave"></div>
                    <div class="sound-wave"></div>
                    <div class="sound-wave"></div>
                  </div>

              </div>
          </div>

          <!-- 面试内容区域 -->
          <div class="interview-content">
              <h3>面试准备就绪</h3>
              <p>您的摄像头已成功开启，可以开始面试了。</p>
              <p v-if="videoError" class="warning">
                  视频加载失败，请尝试：
                  <button @click="retryVideo" class="inline-btn">重新加载视频</button>
              </p>
          </div>
      </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import virtualhuman from './virtualhuman.vue'
import { getVoiceText } from '../api'

const router = useRouter()
const showPermissionModal = ref(true)
const showExitConfirmModal = ref(false)
const userVideo = ref(null)
const permissionError = ref(false)
const errorMessage = ref('')
const videoError = ref(false)
const videoPositionSwitched = ref(false)
const isStartFace = ref(false)
const word = ref(''); // 用于存储识别结果
const isListening = ref(false); // 用于判断是否在语音监听中
let mediaStream = null

//语音转文字
const audioCHangeWord = (async()=>{
    isStartFace.value = true
    // 创建SpeechRecognition对象
    // eslint-disable-next-line no-undef
    var recognition = new webkitSpeechRecognition();
    if (!recognition) {
      // eslint-disable-next-line no-undef
      recognition = new SpeechRecognition();
    }
    // 设置语言
    recognition.lang = 'zh-CN';
    // 开始语音识别
    recognition.start();
    isListening.value = true;
    // 监听识别结果
    recognition.onresult = async(event)=> {
      isStartFace.value = false
      var result = event.results[0][0].transcript;
      console.log(result)
      word.value =(await getVoiceText({text:result})).data.data

    // 监听错误事件
    recognition.onerror = function (event) {
      isStartFace.value = false
      isListening.value = false;
      console.error(event.error);
    };
    // 监听结束事件（包括识别成功、识别错误和用户停止）
    recognition.onend = function () {
      isStartFace.value = false
      isListening.value = false;
      console.log("语音识别停止",word.value);
    };

  }
})



// 处理取消授权请求
const handleCancel = () => {
  router.go(-1)
}

// 显示退出确认弹窗
const showExitConfirm = () => {
  showExitConfirmModal.value = true
}

// 取消退出
const cancelExit = () => {
  showExitConfirmModal.value = false
}

// 确认退出
const confirmExit = () => {
  // 清理资源
  if (mediaStream) {
      mediaStream.getTracks().forEach(track => track.stop())
  }

  // 返回上一个页面
  router.go(-1)
}

// 切换视频和背景位置
const switchPosition = () => {
  videoPositionSwitched.value = !videoPositionSwitched.value
}

// 重试视频加载
const retryVideo = async () => {
  videoError.value = false

  if (mediaStream) {
      mediaStream.getTracks().forEach(track => track.stop())
  }

  await handleConfirm()
}

// 处理确认授权
const handleConfirm = async () => {
  try {
      // 检查navigator.mediaDevices是否存在
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
          throw new Error('您的浏览器不支持摄像头API，请使用Chrome或Firefox最新版本')
      }

      // 请求摄像头和麦克风权限
      mediaStream = await navigator.mediaDevices.getUserMedia({
          video: {
              width: { ideal: 640 },
              height: { ideal: 480 },
              facingMode: "user"  // 使用前置摄像头
          },
          audio: true
      })

      // 授权成功，关闭弹窗
      showPermissionModal.value = false
      permissionError.value = false

      // 将视频流连接到video元素
      if (userVideo.value) {
          userVideo.value.srcObject = mediaStream

          // 显式播放视频
          userVideo.value.play().catch(e => {
              console.error('视频播放失败:', e)
              videoError.value = true
          })
      }
  } catch (err) {
      console.error('无法获取摄像头权限:', err)
      permissionError.value = true
      errorMessage.value = `无法访问摄像头: ${err.message || '请确保您的设备有摄像头并允许浏览器访问'}`
  }
}

// 监听video元素引用变化
watch(() => userVideo.value, (newVal) => {
  if (newVal && mediaStream) {
      newVal.srcObject = mediaStream
      // 尝试显式播放
      newVal.play().catch(e => console.error('视频播放失败:', e))
  }
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (mediaStream) {
      mediaStream.getTracks().forEach(track => track.stop())
  }
})
</script>

<style lang="scss" scoped>
.video-interview-container {
  background: linear-gradient(135deg, #e6f3ff 0%, #b6d9ff 100%);
  min-height: 100vh;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;

  // 授权弹窗样式
  .permission-modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;

      .modal-content {
          width: 90%;
          max-width: 360px;
          background-color: white;
          border-radius: 16px;
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
          overflow: hidden;

          .modal-header {
              padding: 20px;
              text-align: center;
              border-bottom: 1px solid #f0f0f0;

              .modal-icon {
                  width: 48px;
                  height: 48px;
                  margin-bottom: 12px;
              }

              h2 {
                  font-size: 18px;
                  color: #333;
                  font-weight: 600;
                  margin: 0;
              }
          }

          .modal-body {
              padding: 20px;

              p {
                  margin: 10px 0;
                  font-size: 14px;
                  color: #666;
                  line-height: 1.5;

                  strong {
                      color: #4a90e2;
                  }
              }

              .error-message {
                  margin-top: 15px;
                  padding: 10px;
                  background-color: #fff5f5;
                  border-left: 3px solid #ff4d4f;
                  border-radius: 4px;

                  p {
                      color: #f5222d;
                      margin: 5px 0;
                  }

                  ul {
                      margin: 8px 0 0 16px;
                      padding: 0;

                      li {
                          font-size: 12px;
                          color: #666;
                          margin-bottom: 4px;
                      }
                  }
              }
          }

          .modal-footer {
              padding: 15px 20px;
              display: flex;
              justify-content: space-between;
              border-top: 1px solid #f0f0f0;

              button {
                  flex: 1;
                  padding: 12px 0;
                  border-radius: 8px;
                  font-size: 15px;
                  font-weight: 500;
                  cursor: pointer;
                  transition: all 0.3s;

                  &.cancel-btn {
                      margin-right: 10px;
                      background-color: #f5f5f5;
                      color: #666;
                      border: none;

                      &:hover {
                          background-color: #ebebeb;
                      }
                  }

                  &.confirm-btn {
                      background-color: #4a90e2;
                      color: white;
                      border: none;

                      &:hover {
                          background-color: #357abd;
                      }
                  }

                  &.exit-btn {
                      background-color: #ff4d4f;

                      &:hover {
                          background-color: #ff7875;
                      }
                  }
              }
          }
      }
  }

  // 视频区域样式
  .video-section {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 10px; // 减少内边距，让内容更大
      position: relative;

      // 返回按钮
      .back-button {
          position: absolute;
          top: 15px;
          left: 15px;
          display: flex;
          align-items: center;
          background-color: rgba(0, 0, 0, 0.5);
          color: white;
          padding: 8px 12px;
          border-radius: 20px;
          cursor: pointer;
          z-index: 10;

          .back-icon {
              width: 8px;
              height: 8px;
              border-top: 2px solid white;
              border-left: 2px solid white;
              transform: rotate(-45deg);
              margin-right: 6px;
          }

          span {
              font-size: 14px;
          }

          &:hover {
              background-color: rgba(0, 0, 0, 0.7);
          }
      }

      .interview-container {
          flex: 1; // 使容器占据所有可用空间
          position: relative;
          width: 100%;
          max-width: 100%; // 取消最大宽度限制
          margin: 10px auto; // 减少上下边距
          border-radius: 16px;
          overflow: hidden;
          min-height: 70vh; // 确保最小高度占据视窗大部分
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);


          // 背景图区域
          .background-area {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              z-index: 1;

              .background-image {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
              }
          }

          // 视频区域
          .video-area {
              position: absolute;
              top: 10px;
              right: 10px;
              width: 30%;
              aspect-ratio: 4 / 3;
              z-index: 2;
              border-radius: 8px;
              overflow: hidden;
              border: 2px solid white;
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
              cursor: pointer;
              transition: all 0.3s ease;

              .user-video {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                  background-color: #333;
              }

              &:hover {
                  transform: scale(1.02);
              }
          }

          // 语音图标
          .sound-icon-container {
              position: absolute;
              bottom: 20px;
              left: 50%;
              transform: translateX(-50%);
              z-index: 3;
              display: flex;
              flex-direction: column;
              align-items: center;

              .sound-icon {
                  width: 40px;
                  height: 40px;
                  margin-bottom: 8px;
                  filter: drop-shadow(0 0 4px rgba(255, 255, 255, 0.8));
              }

              // 声波动画
              .sound-wave {
                  position: absolute;
                  bottom: 0;
                  width: 10px;
                  height: 10px;
                  background-color: #4a90e2;
                  border-radius: 50%;
                  transform: scale(0);
                  opacity: 0.8;
                  animation: sound-wave-animation 1.5s infinite;

                  &:nth-child(2) {
                      animation-delay: 0s;
                  }

                  &:nth-child(3) {
                      animation-delay: 0.5s;
                  }

                  &:nth-child(4) {
                      animation-delay: 1s;
                  }
              }
          }

          // 位置切换后的样式
          &.switched {
              .video-area {
                  top: 0;
                  right: 0;
                  width: 100%;
                  height: 100%;
                  border-radius: 0;
                  border: none;
                  z-index: 1;
              }

              .background-area {
                  top: 10px;
                  right: 10px;
                  left: auto;
                  width: 30%;
                  height: auto;
                  aspect-ratio: 4 / 3;
                  z-index: 2;
                  border-radius: 8px;
                  overflow: hidden;
                  border: 2px solid white;

                  .background-image {
                      width: 100%;
                      height: 100%;
                      object-fit: cover;
                  }
              }
          }
      }

      .interview-content {
          margin-top: 10px; // 减少上边距
          background-color: white;
          border-radius: 12px;
          padding: 15px; // 减少内边距
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
          max-height: 100px; // 限制信息区域高度
          overflow-y: auto; // 添加滚动条，以便内容过多时可滚动

          h3 {
              font-size: 16px; // 稍微减小标题大小
              margin-bottom: 5px; // 减少下边距
          }

          p {
              font-size: 14px;
              margin: 5px 0; // 减少段落间距
              line-height: 1.4; // 稍微减小行高
          }

          .warning {
              color: #faad14;
              font-size: 14px;
              margin-top: 10px;
              background-color: #fffbe6;
              padding: 8px 12px;
              border-radius: 4px;
              border-left: 3px solid #faad14;
          }

          .inline-btn {
              background: none;
              border: none;
              color: #4a90e2;
              text-decoration: underline;
              cursor: pointer;
              padding: 0;
              font-size: inherit;

              &:hover {
                  color: #357abd;
              }
          }
      }
  }
}

// 声波动画
@keyframes sound-wave-animation {
  0% {
      transform: scale(0);
      opacity: 0.8;
  }
  70% {
      transform: scale(3);
      opacity: 0;
  }
  100% {
      transform: scale(0);
      opacity: 0;
  }
}

/* 媒体查询，针对不同屏幕尺寸优化 */
@media (min-height: 700px) {
  .video-section .interview-container {
      min-height: 75vh; // 在较高的屏幕上占据更多空间
  }
}

@media (min-height: 900px) {
  .video-section .interview-container {
      min-height: 80vh; // 在更高的屏幕上占据更多空间
  }
}
</style>